package com.cskaoyan.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    // 获取SQLSession
    static SqlSession sqlSession;

    static {

        // 如何去构建SQLsession呢？
        // 1. 获取SQLsessionFactoryBuilder  // 建造者模式
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        // 2. 获取SqlSessionFactory // 工厂模式，是用来生产SqlSession的
//        ClassLoader classLoader = MybatisUtils.class.getClassLoader();
//        InputStream inputStream = classLoader.getResourceAsStream("mybatis-config.xml");

        InputStream in = null;
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }

        SqlSessionFactory sqlSessionFactory = builder.build(in);

        // 3.  生产sqlSession sqlSession可以理解为之间JDBC里面的connection，sqlSession可以用来去执行SQL语句
        sqlSession = sqlSessionFactory.openSession();

    }

    // 获取SqlSession
    public static SqlSession getSqlSession() {
        return sqlSession;
    }
}
